import { ftCreate, ftDelete, ftPage, ftUpdate, IpageData } from '@/service/modules/tag';
import { Iresponse } from '@/service/require/type';
import { message } from 'antd';
import { useState } from 'react';

export default () => {
  const [pageData, setPageData] = useState<IpageData[]>([]);
  const [pagePagination, setPagePagination] = useState({
    total: 0,
    current: 1,
    size: 10,
  });
  const [pageParams, setPageParams] = useState<any>({});

  // 分页
  async function pageDataAction(params: any = {}) {
    try {
      const res = await ftPage({
        pageNum: 1,
        pageSize: 10,
        text: '',
        ...params,
      });
      const { code, data, message, total } = res;
      if (code === 500) {
        throw new Error(message?.message || '服务器失败');
      }
      setPageData(data || []);
      setPagePagination({
        ...pagePagination,
        total: total || 0,
      });
    } catch (error: any) {
      message.error(error.message);
    }
  }

  // 删除
  async function deleteAction(ids: string[], _update: boolean) {
    return new Promise(async (resolve, reject) => {
      try {
        const res = await ftDelete(ids);
        if (_update) {
          pageDataAction(pageParams);
        }
        message.success(res.message);
        resolve(res);
      } catch (error) {
        reject(error);
      }
    });
  }

  // 创建
  async function createAction(_row: any, _update: boolean) {
    return new Promise<Iresponse>(async (resolve, reject) => {
      try {
        const res = await ftCreate(_row);
        if (_update) {
          pageDataAction(pageParams);
        }
        resolve(res);
      } catch (error) {
        message.error('内部错误');
      }
    });
  }

  // 修改
  async function updateAction(_row: any, _update: boolean) {
    return new Promise<Iresponse>(async (resolve, reject) => {
      try {
        const res = await ftUpdate(_row);
        if (_update) {
          pageDataAction(pageParams);
        }
        resolve(res);
      } catch (error) {
        message.error('内部错误');
      }
    });
  }

  return {
    pageData,
    pagePagination,
    pageDataAction,
    setPagePagination,
    pageParams,
    setPageParams,
    deleteAction,
    createAction,
    updateAction,
  };
};
